/**
 * Created by wry on 2015/5/14.
 */
var toolUtil = require('../../common/utils/toolUtil');
var mysqlUtil = require('../../common/utils/mysqlUtil');
var users = mongoose.model('user');
var async = require('async');
var moment = require('moment');
var community = mongoose.model('community');


exports.getActivityListForPage = function (input, callback) {

    var currentPage = 1;
    if (input.currentPage != '' && input.currentPage != null) {
        currentPage = input.currentPage;
    }
    var pageSize = 10;
    var offset = (currentPage - 1) * pageSize;

    var getSql = function (type) {
        var sql = "select distinct " + type + " from lottery_activity as la left join lottery_activity_community_map as lacm on la.id = lacm.lottery_id";
        return sql;
    }

    var communityName = input.communityName;
    var activityName = input.activityName;

    var communityList = new Array();

    async.series([

        function (callbackInner) {
            community.find({communityName: {$regex: communityName}}, '_id', function (err, cy) {
                if (cy != null && cy.length > 0) {
                    for (var i = 0; i < cy.length; i++) {
                        communityList.push("'" + cy[i]._id + "'");
                    }
                }
                callbackInner();
            });
        },

        function (callbackInner) {

            var sql = getSql("la.*") + " where 1 = 1 ";

            if (communityList.length > 0) {
                sql += "and lacm.community_id in (" + communityList.toString() + ") ";
            } else if (communityName != null) {
                sql += "and lacm.community_id in ('not found') "
            }

            if (activityName != null) {
                sql += " and la.activity_name like '%" + activityName + "%'";
            }

            sql += ' order by la.create_time desc limit ' + offset + ' ,' + pageSize;

            mysqlUtil.query(sql, function (err, result) {
                callbackInner(err, result);
            });
        },
        function (callbackInner) {
            var sql = getSql("count(*) as count") + " where 1 = 1 ";

            if (communityList.length > 0) {
                sql += "and lacm.community_id in (" + communityList.toString() + ") ";
            } else if (communityName != null) {
                sql += "and lacm.community_id in ('not found') "
            }

            if (activityName != null) {
                sql += " and la.activity_name like '%" + activityName + "%'";
            }

            mysqlUtil.query(sql, function (err, result) {
                var count = result[0].count;
                var totalPage = Math.ceil(count / pageSize);
                callbackInner(err, totalPage);
            });
        }
    ], callback)

};

exports.getProducts = function (input, callback) {

    var currentPage = 1;
    if (input.currentPage != '' && input.currentPage != null) {
        currentPage = input.currentPage;
    }
    var pageSize = 10;
    var offset = (currentPage - 1) * pageSize;

    var getSql = function (type) {
        var sql = "select " + type + " from lottery_product where 1 = 1 ";

        if (input.productName != null && input.productName != '') {
            sql += " and name = '" + input.productName + "'";
        }

        sql += " order by create_time desc ";
        return sql;
    }

    async.series([

        function (callbackInner) {

            var sql = getSql("*");


            mysqlUtil.query(sql, function (err, result) {
                callbackInner(err, result);
            });
        },
        function (callbackInner) {
            var sql = getSql("count(*) as count");

            mysqlUtil.query(sql, function (err, result) {
                var count = result[0].count;
                var totalPage = Math.ceil(count / pageSize);
                callbackInner(err, totalPage);
            });
        }
    ], callback)

};

exports.addProduct = function (input, callback) {

    var productName = input.productName;
    var inventory = input.inventory;
    var type = input.type;

    var sql = "insert into lottery_product (name,total_inventory,comsume_total_inventory,inventory,type,is_use,create_time) "
        + "values ('" + productName + "'," + inventory + ",0," + inventory + "," + type + ",1," + new Date().getTime() + ")";

    mysqlUtil.query(sql, callback);

};

exports.deleteProduct = function (input, callback) {

    var id = input.id;

    var sql = "delete from lottery_product where id = " + id;

    mysqlUtil.query(sql, callback);

};

exports.findProductById = function (input, callback) {

    var id = input.id;

    var sql = "select * from lottery_product where id = " + id;

    mysqlUtil.query(sql, function (err, result) {
        callback(err, result);
    });

};

exports.updateProductInventory = function (input, callback) {

    var id = input.id;
    var inventoryType = input.inventoryType;
    var updateInventory = input.updateInventory;

    var sql = "";

    if (inventoryType == 0) {
        sql = "update lottery_product set inventory = (inventory - " + updateInventory + ") , comsume_total_inventory = (comsume_total_inventory +" + updateInventory + ") where id = " + id;
    } else if (inventoryType == 1) {
        sql = "update lottery_product set inventory = (inventory + " + updateInventory + ") , total_inventory = (total_inventory +" + updateInventory + ") where id = " + id;
    }

    mysqlUtil.query(sql, callback);

};

exports.getCommunitysByLotteryId = function (input, callback) {

    var currentPage = 1;
    if (input.currentPage != '' && input.currentPage != null) {
        currentPage = input.currentPage;
    }
    var pageSize = 10;
    var offset = (currentPage - 1) * pageSize;


    var lotteryId = input.lotteryId;

    async.series([

        function (callbackInner) {

            var sql = "select community_id from lottery_activity_community_map where lottery_id = " + lotteryId;

            mysqlUtil.query(sql, function (err, result) {
                var communityIds = new Array();
                for (var i = 0; i < result.length; i++) {
                    communityIds.push(result[i].community_id);
                }
                community.find({_id: {$in: communityIds}}, function (err, communityList) {
                    callbackInner(err, communityList);
                });
            });
        },
        function (callbackInner) {
            var sql = "select count(*) as count from lottery_activity_community_map where lottery_id = " + lotteryId;

            mysqlUtil.query(sql, function (err, result) {
                var count = result[0].count;
                var totalPage = Math.ceil(count / pageSize);
                callbackInner(err, totalPage);
            });
        }
    ], callback)

};

exports.deleteLotteryCommunityMap = function (input, callback) {

    var lotteryId = input.lotteryId;
    var communityId = input.communityId;

    var sql = "delete from lottery_activity_community_map where lottery_id = " + lotteryId + " and community_id = '" + communityId + "'";

    mysqlUtil.query(sql, callback);

};

exports.getPrizeByLotteryId = function (input, callback) {

    var currentPage = 1;
    if (input.currentPage != '' && input.currentPage != null) {
        currentPage = input.currentPage;
    }
    var pageSize = 10;
    var offset = (currentPage - 1) * pageSize;

    var lotteryId = input.lotteryId;

    var getSql = function (type) {
        var sql = "select " + type + " from lottery_prize lp left join lottery_product lp2 on lp.product_id = lp2.id where lottery_id = " + lotteryId;
        return sql;
    }

    async.series([

        function (callbackInner) {

            var sql = getSql("lp.*,lp2.name as prize_name") + " order by prize_position limit " + offset + "," + pageSize;

            mysqlUtil.query(sql, function (err, result) {
                callbackInner(err, result);
            });
        },
        function (callbackInner) {
            var sql = getSql("count(*) as count ");

            mysqlUtil.query(sql, function (err, result) {
                var count = result[0].count;
                var totalPage = Math.ceil(count / pageSize);
                callbackInner(err, totalPage);
            });
        }
    ], callback)

};

exports.deletePrize = function (input, callback) {

    var prizeId = input.prizeId;

    var sql = "delete from lottery_prize where id = " + prizeId;

    mysqlUtil.query(sql, callback);

};

exports.getAllProduct = function (input, callback) {

    var sql = "select * from lottery_product";

    mysqlUtil.query(sql, callback);

};

exports.addPrize = function (input, callback) {
    var productId = input.productId;
    var levelName = input.levelName;
    var prizeCount = input.prizeCount;
    var rewardCount = input.rewardCount;
    var prizeLevel = input.prizeLevel;
    var lotteryId = input.lotteryId;
    var prizePic = input.prizePic;
    var prizePosition = input.prizePosition;
    var prizeProbability = input.prizeProbability;

    logger.info(prizePic);
    logger.info(prizePosition);
    logger.info(prizeProbability);

    var sql = "insert into lottery_prize (lottery_id,product_id,level_name,prize_count,reward_count,prize_level,create_time,prize_pic,prize_position,prize_probability) values"
        + "(" + lotteryId + "," + productId + ",'" + levelName + "'," + prizeCount + "," + rewardCount + "," + prizeLevel + "," + new Date().getTime() + ",'" + prizePic + "'," + prizePosition + "," + prizeProbability + ")";

    mysqlUtil.query(sql, callback);

};

exports.getLotteryPrizeById = function (input, callback) {

    var prizeId = input.prizeId;

    var sql = "select lp.* , lp2.name as name from lottery_prize lp left join lottery_product lp2 on lp.product_id = lp2.id where lp.id = " + prizeId;

    mysqlUtil.query(sql, callback);

};

exports.updateLotteryPrize = function (input, callback) {

    var prizeId = input.prizeId;
    var levelName = input.levelName;
    var prizeCount = input.prizeCount;
    var rewardCount = input.rewardCount;
    var prizeLevel = input.prizeLevel;
    var prizeProbability = input.prizeProbability;
    var prizePosition = input.prizePosition;
    var prizePic = input.prizePic;

    var sql = "update lottery_prize set prize_probability = " + prizeProbability + ",prize_position = " + prizePosition + ", level_name = '" + levelName + "' , prize_count = " + prizeCount + ", reward_count = " + rewardCount + ",prize_level = " + prizeLevel;
    if (prizePic != null && prizePic != '') {
        sql += ", prize_pic = '" + prizePic + "'";
    }
    sql += " where id =" + prizeId;

    mysqlUtil.query(sql, callback);

};

exports.getLotteryAward = function (input, callback) {

    var currentPage = 1;
    if (input.currentPage != '' && input.currentPage != null) {
        currentPage = input.currentPage;
    }
    var pageSize = 10;
    var offset = (currentPage - 1) * pageSize;

    var lotteryId = input.lotteryId;

    var getSql = function (type) {
        var sql = "select " + type + " from lottery_award as la left join lottery_prize as lp on la.prize_id = lp.id left join lottery_product as lp2 on lp.product_id = lp2.id where la.lottery_id = " + lotteryId;
        return sql;
    }

    async.series([

        function (callbackInner) {

            var sql = getSql("la.* ,lp2.name as prizeName,lp.level_name as levelName") + " limit " + offset + "," + pageSize;

            logger.info(sql);

            mysqlUtil.query(sql, function (err, result) {
                async.each(result, function (temp, callbackInner) {
                    community.findOne({_id: temp.community_id}, function (err, community) {
                        if (community != null)
                            temp.communityName = community.communityName == null ? "" : community.communityName;
                        users.findOne({_id: temp.user_id}, function (err, user) {
                            temp.nickName = user.nickName;
                            callbackInner();
                        });
                    })
                }, function (err) {
                    callbackInner(err, result);
                })
            });
        },
        function (callbackInner) {
            var sql = getSql("count(*) as count ");

            mysqlUtil.query(sql, function (err, result) {
                var count = result[0].count;
                var totalPage = Math.ceil(count / pageSize);
                callbackInner(err, totalPage);
            });
        }
    ], callback)

};

exports.addLottery = function (input, callback) {

    var activityName = input.activityName;
    var communityIds = input.communityIds;
    var limitCount = input.limitCount;
    var activityDesc = input.activityDesc;
    var ruleDesc = input.ruleDesc;
    var activityBeginTime = input.activityBeginTime;
    var activityEndTime = input.activityEndTime;
    var isPublish = input.isPublish;

    var sql = "insert into lottery_activity (activity_name,lottery_limit,activity_desc,rule_desc,begin_time,end_time,is_publish,create_time) values"
        + "('" + activityName + "'," + limitCount + ",'" + activityDesc + "','" + ruleDesc + "'," + new Date(activityBeginTime).getTime() + "," + new Date(activityEndTime).getTime() + "," + isPublish + "," + new Date().getTime() + ")";

    var lotteryId = "";

    async.series([

        function (callbackInner) {
            mysqlUtil.query(sql, function (err, result) {
                callbackInner(err, result);
            });
        },
        function (callbackInner) {
            var selSql = "select max(id) as id from lottery_activity where activity_name = '" + activityName + "'";

            mysqlUtil.query(selSql, function (err, result) {
                lotteryId = result[0].id;

                callbackInner();
            });
        },
        function (callbackInner) {
            async.each(communityIds, function (communityId, callbackInner) {
                var insertSql = "insert into lottery_activity_community_map values (" + lotteryId + ",'" + communityId + "')";
                mysqlUtil.query(insertSql, callbackInner);
            }, function () {
                callback();
            })
        }

    ], callback)
};

exports.deleteLottery = function (input, callback) {

    var lotteryId = input.lotteryId;

    var sql = "delete from lottery_activity where id = " + lotteryId;

    mysqlUtil.query(sql, callback);

};

exports.getLotteryById = function (input, callback) {

    var lotteryId = input.lotteryId;

    var sql = "select * from lottery_activity where id = " + lotteryId;

    mysqlUtil.query(sql, function (err, lottery) {
        sql = "select community_id from lottery_activity_community_map where lottery_id = " + lottery[0].id;
        mysqlUtil.query(sql, function (err, communities) {
            lottery[0].communities = communities;
            callback(err, lottery);
        })
    });

};

exports.updateLottery = function (input, callback) {

    var lotteryId = input.lotteryId;
    var activityName = input.activityName;
    var limitCount = input.limitCount;
    var activityDesc = input.activityDesc;
    var ruleDesc = input.ruleDesc;
    var activityBeginTime = input.activityBeginTime;
    var activityEndTime = input.activityEndTime;
    var communityIds = input.communityIds;

    var sql = "update lottery_activity set activity_name = '" + activityName + "',lottery_limit = " + limitCount + ",activity_desc = '" + activityDesc + "',rule_desc = '" + ruleDesc + "' ";

    if (activityBeginTime != null) {
        sql += " , begin_time = " + new Date(activityBeginTime).getTime();

    }
    if (activityEndTime != null) {
        sql += " , end_time = " + new Date(activityEndTime).getTime();
    }

    sql += ", update_time=" + new Date().getTime() + " where id = " + lotteryId;

    mysqlUtil.query(sql, function () {
        sql = "delete from lottery_activity_community_map where lottery_id = " + lotteryId;
        mysqlUtil.query(sql, function () {
            sql = "insert into lottery_activity_community_map (lottery_id ,community_id) values ";
            for (var i = 0; i < communityIds.length; i++) {
                if (i == 0) {
                    sql += "(" + lotteryId + ",'" + communityIds[i] + "')";
                } else {
                    sql += ",(" + lotteryId + ",'" + communityIds[i] + "')";
                }
            }
            mysqlUtil.query(sql, callback);
        })
    });

};